# !/usr/bin/env
# -*- coding:utf-8 -*-
# __author__='AChan'
import pymysql as mysql
import requests
import time
import json
import threading


# 获取当前时间戳
def get_init_time():
    totime = time.time()
    totime = int(totime)
    return totime


def get_date(timestamp = False):
    if timestamp is False:
        timestamp = get_init_time()
    time_local = time.localtime(timestamp)
    return time.strftime("%Y-%m-%d %H:%M:%S", time_local)


class MyThread(threading.Thread):
    def __init__(self, datas, url):
        self.datas = datas
        self.url = url
        self.sporttery_team_venue_fields = ['venue_name', 'capacity', 'venue_id']
        self.sporttery_team_result_fields = ['club_name', 'club_abbr_name', 'team_city', 'team_founded', 'team_pic', 'competition_name', 'competition_abbr_name', 'rank', 'win', 'draw', 'lose', 'coach', 'team_id']
        super(MyThread, self).__init__()

    def run(self):
        try:
            count = 0
            conn = mysql.Connection('114.113.147.243', 'fucheng', 'fucheng@123', 'sportsfish', 8666, charset = 'utf8')
            cur = conn.cursor()  # 获取一个游标
            # teamFields = ['team_pic', 'club_name', 'club_abbr_name', 'team_founded', 'team_city', 'venue_name', 'capacity','coach', 'competition_name', 'competition_abbr_name', 'rank', 'win', 'draw', 'lose']
            # matches = []
            json_venue = "venue"
            venue = self.datas[json_venue]
            fields = []
            for field in self.sporttery_team_result_fields:
                new_result = self.datas[field]
                if new_result is "" or new_result is None:
                    fields.append("0")
                else:
                    new_result = new_result.replace("'", '')
                    fields.append("'" + new_result + "'")
            new_dict = {}
            for val in venue:
                for key in self.sporttery_team_venue_fields:
                    new_val = venue[val][key]
                    new_val = new_val.replace("'", "")
                    new_dict[key] = new_val
            for key in self.sporttery_team_venue_fields:
                if new_dict:
                    fields.append("'" + new_dict[key] + "'")
                else:
                    fields.append("0")
            team_insert_sql = "INSERT INTO jingcai_sports_team_info_tmp(club_name, club_abbr_name, team_city, team_founded,  team_pic, competition_name, competition_abbr_name, rank, win, draw, lose, coach, team_id, venue_name, capacity, venue_id, add_time, mod_time) VALUES"
            fields.append("'%s'" % get_date())
            fields.append("'%s'" % get_date())
            team_value_sql = ','.join(fields)
            duplicate_sql = " ON DUPLICATE KEY UPDATE club_name=values(club_name),club_abbr_name=values(club_abbr_name),team_city=values(team_city),team_founded=values(team_founded),team_pic=values(team_pic),competition_name=values(competition_name),competition_abbr_name=values(competition_abbr_name),rank=values(rank),win=values(win),draw=values(draw),lose=values(lose),venue_name=values(venue_name),capacity=values(capacity),coach=values(coach),add_time=values(add_time),mod_time=values(mod_time),team_id=values(team_id)"
            insert_sql = "%s (%s)%s" % (team_insert_sql, team_value_sql, duplicate_sql)
            print(insert_sql)
            cur.execute(insert_sql)
            count += cur.rowcount
            print("共插入%s条数据" % count)
        except Exception as e:
            print("发生异常:%s" % e)
            conn.rollback()
            print("当前采集地址:%s" % url)
            exit(0)
        finally:
            conn.commit()
            cur.close()
            conn.close()


start = time.time()
threads = []
for i in range(60, 100000):
    # print("第%s页=====================" % str(i))
    url = "http://i.sporttery.cn/api/fb_match_info/get_team_data/?f_callback=footb_info&tid=%d" % i

    data = requests.get(url)
    data = str(data.text).replace("footb_info(", "")
    data = data.replace(");", "")
    data = json.loads(data)
    if data['status']['code'] != 0:
        continue
    else:
        result = data['result']
        if 'club_name' not in result.keys():
            continue
        t = MyThread(data['result'], url)
        threads.append(t)
        t.setDaemon(True)
        t.start()
for t in threads:
    t.join()

print("Elapsed time: %s" % (time.time() - start))
